<template>
  <section class="todoapp">
    <hm-header @add-event="handleAdd" ></hm-header>
    <hm-main 
    :list ="showList" 
    @delete-event ="handleDelete"
    @change-status-event="changeStatus"
    @change-all-event="handleAll"
    ></hm-main>
    <hm-footer 
    :list ="list" 
    @clear-All="chearAll" :stauts="stauts" 
    @stauts-event="stauts = $event"></hm-footer>
  </section>
</template>

<script>
const obj = {
  "#/": "all",
  "#/completed": "done",
  "#/active": "undone",
};
import HmHeader from './components/hm-header.vue'
import HmMain from './components/hm-main.vue'
import HmFooter from './components/hm-footer.vue'
export default {
  components: {
    HmHeader,
    HmMain,
    HmFooter
  },
  data(){
    return{
      list: JSON.parse(window.localStorage.getItem("list"))||[],
      stauts: obj[ location.hash] ||'all', //约定all 代表的是全部，done代表的是显示已完成，undone未完成
    }
  },
  methods:{
      handleDelete(id){
         const index =this.list.findIndex((item)=>item.id===id);
         this.list.splice(index, 1);
      },
      changeStatus(id){
         const obj =this.list.find((item)=>item.id=== id);
         obj.done =!obj.done;
      },
      handleAdd(name){
          const id = this.list.length === 0 ? 1:this.list.slice(-1)[0].id+1;
          const obj={
              id,
              name,
              done:false,
          };
          this.list.push(obj)
      },
      handleAll(value){
        this.list = this.list.map((item) =>{
          item.done = value;
          return item;
        })

      },
      chearAll(){
        this.list = this.list.filter((item) =>item. done ===false)
      
        }
  },
  computed:{
    showList(){
      if(this.stauts === 'all'){
        return this.list; 
      }else if(this.stauts === 'done'){
        return this.list.filter((item)=>item. done ===true);
      }else{
        return this.list.filter((item) =>item. done ===false)
      }
    }
  },
  watch:{
    list:{
      handler(nowValue){
        window.localStorage.setItem("list", JSON.stringify(nowValue))
    },
    deep:true  //开启深度监听
    }
  
  }
}
</script>

<style></style>
